package com.tcs.gamed.server.service;

import java.util.ArrayList;
import java.util.List;

import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;
import com.tcs.gamed.client.service.FolderService;
import com.tcs.gamed.server.model.Folder;
import com.tcs.gamed.server.meta.FolderItemMeta;
import com.tcs.gamed.shared.model.FolderItem;

public class FolderServiceImpl implements FolderService {

    public FolderItem getItem(String key) {
        return Datastore.get(
            FolderItemMeta.get(),
            Datastore.stringToKey(key))
            .makeSharedFolderItem();
    }

    public List<FolderItem> getChildren(String key) {
        final Key keyObj = (key == null) ? null : Datastore.stringToKey(key);
        final FolderItemMeta m = FolderItemMeta.get();
        final Iterable<com.tcs.gamed.server.model.FolderItem> iter
            = Datastore.query(m)
                .filter(m.parentRef.equal(keyObj))
                .asIterable();
        
        final List<FolderItem> list = new ArrayList<FolderItem>();
        for(com.tcs.gamed.server.model.FolderItem i : iter) {
            list.add(i.makeSharedFolderItem());
        }
        return list;
    }

    public FolderItem makeFolder(String name, String comment, String parentKey) {
        final Folder folder = new Folder();
        folder.setName(name);
        folder.setComment(comment);
        
        if(parentKey != null) {
            folder.getParentRef().setKey(
                Datastore.stringToKey(parentKey));
        }
        
        Datastore.put(folder);
        return folder.makeSharedFolderItem();
    }

    public FolderItem editFolder(String key, String name, String comment,
            String parentKey) {
        final Folder folder = Datastore.get(Folder.class, Datastore.stringToKey(key));
        folder.setName(name);
        folder.setComment(comment);
        
        if(parentKey != null) {
            folder.getParentRef().setKey(
                Datastore.stringToKey(parentKey));
        }
        Datastore.put(folder);
        
        return folder.makeSharedFolderItem();
    }
}
